package com.chhuang.ewcrm.controller;

import com.chhuang.ewcrm.bean.QueryBean;
import com.chhuang.ewcrm.consts.EwcrmConstants;
import com.chhuang.ewcrm.date.DateUtil;
import com.chhuang.ewcrm.entity.*;
import com.chhuang.ewcrm.service.*;
import com.chhuang.ewcrm.string.MoneyUtil;
import com.chhuang.ewcrm.vo.ResultBean;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author chhuang
 * @create 2020-11-18-7:43
 */
@RestController
@RequestMapping("wapi/sell")
public class WSellController {
    Logger logger= LoggerFactory.getLogger(WSellController.class);

    /**
     * 服务对象
     */
    @Resource
    private ESellService eSellService;
    @Resource
    private ESellGoodsService eSellGoodsService;
    @Resource
    private EWarehouseService eWarehouseService;
    @Resource
    private EMaxNumberService eMaxNumberService;
    @Resource
    private SysConfigService sysConfigService;

    /**
     * 保存销售记录
     * @param eSell
     * @return
     */
    @PutMapping("saveSellRecord")
    public synchronized ResultBean<ESell> saveSellRecord(@RequestBody ESell eSell){
        ResultBean<ESell> resultBean = new ResultBean<>();
        resultBean.setSuccess(false);

        if(StringUtils.isNotEmpty(eSell.getLicensePlate()) && eSell.getGrossWeight()!=null &&
                eSell.getTareWeight()!=null && eSell.getNetWeight()!=null){

            String warehouseEname = null;
            if(StringUtils.isNotEmpty(eSell.getWarehouseId())) {//指定仓库
                EWarehouse eWarehouse = eWarehouseService.queryById(eSell.getWarehouseId());
                warehouseEname = eWarehouse.getWarehouseEname();
            }
            String number = createNewNumber(eSell.getOutTime(), warehouseEname, EwcrmConstants.WEIGH_TYPES[0]);

            if(StringUtils.isNotEmpty(number)){
                eSell.setSellNumber(number);

                if(!eSell.getIsDelivered() && eSell.getSellPrice()!=null){//不是送到
                    eSell.setPaymentAmount(eSell.getNetWeight()*eSell.getSellPrice()-(eSell.getDeductionMoney()==null?0:eSell.getDeductionMoney()));
                    eSell.setPaymentAmountCh(MoneyUtil.moneyToChinese(BigDecimal.valueOf(eSell.getPaymentAmount())));
                    eSell.setTotalAmount(eSell.getPaymentAmount());
                    eSell.setSellAveragePrice(eSell.getTotalAmount()/eSell.getNetWeight());
                }
                Date now = new Date();
                eSell.setModifyTime(now);
                eSell.setCreateTime(now);
                eSell.setStatus(1);//过磅完成

                resultBean.setData(eSellService.insert(eSell));
                resultBean.setSuccess(true);
            }else
                resultBean.setMessage("请联系管理员维护码单号");
        }else
            resultBean.setMessage("参数不为空");

        logger.debug(resultBean.toString());
        return resultBean;
    }

    /**
     * 创建码单编号
     * @param outTime
     * @param warehouseEname
     * @param weighTypeEname
     * @return
     */
    private String createNewNumber(Date outTime, String warehouseEname, String weighTypeEname){
        String number = null;
        SysConfig config = sysConfigService.queryById("number_mode");
        if(config!=null && "2".equals(config.getConfigValue())){//日期编号方式编号
            ESell tmp = new ESell();
            String outDate = DateUtil.date2String(outTime, DateUtil.YYYYMMDD);
            tmp.setSellNumber(warehouseEname+weighTypeEname+outDate);
            List<ESell> eList = eSellService.queryLike(tmp, "sell_number desc");
            if(eList!=null && !eList.isEmpty()){
                tmp = eList.get(0);
                String lastNum = tmp.getSellNumber();
                number = lastNum.substring(0, lastNum.length()-3) +
                        String.format("%03d", Integer.parseInt(lastNum.substring(lastNum.length()-3))+1);
            }else {
                number = tmp.getSellNumber() + String.format("%03d", 1);
            }
        }else {//数字叠加编号
            number = eMaxNumberService.getNumber(warehouseEname, EwcrmConstants.WEIGH_TYPES[1]);
        }
        return  number;
    }

    /**
     * 表格查询
     * @param queryBean
     * @return
     */
    @PostMapping("/queryPage")
    public ResultBean<PageInfo<ESell>> query(@RequestBody QueryBean<ESell> queryBean){
        logger.debug(queryBean.toString());
        ResultBean<PageInfo<ESell>> resultBean = new ResultBean<>();

        PageInfo<ESell> pageInfo = null;
        List<ESell> sells = null;
        if(queryBean!=null) {
            if (StringUtils.isNotEmpty(queryBean.getOrderBy()))
                pageInfo = eSellService.queryLike(queryBean.getQuery(), queryBean.getPageNum(), queryBean.getPageSize(), queryBean.getOrderBy());
            else
                pageInfo = eSellService.queryLike(queryBean.getQuery(), queryBean.getPageNum(), queryBean.getPageSize());
            resultBean.setData(pageInfo);
            resultBean.setSuccess(true);
            resultBean.setCode(queryBean.getDraw());
        }else {
            resultBean.setSuccess(false);
            resultBean.setMessage("参数不为空");
        }

        logger.debug(resultBean.toString());
        return resultBean;
    }

    /**
     * 作废过磅记录
     * @param id
     * @return
     */
    @DeleteMapping("toInvalid/{id}/{remark}")
    public ResultBean<?> toInvalid(@PathVariable("id") String id, @PathVariable("remark") String remark){
        ResultBean<?> resultBean = new ResultBean<>();
        resultBean.setSuccess(false);

        ESell eSell = this.eSellService.queryById(id);
        if(eSell!=null){
            Date now = new Date();

            if(eSell.getStatus()==2){//原来是确认完成的过磅单，作废后要减去对应的库存
                ESellGoods goods = eSellGoodsService.queryById(eSell.getSellGoodsId());
                if(goods!=null){
                    goods.setSellTotalWeight(goods.getSellTotalWeight()-eSell.getNetWeight());
                    goods.setSellTotalAmount(goods.getSellTotalAmount()-eSell.getTotalAmount());
                    goods.setSellAveragePrice(goods.getSellTotalAmount()/goods.getSellTotalWeight());
                    goods.setModifyTime(now);
                    eSellGoodsService.update(goods);
                }else {
                    logger.error("作废的销售记录，对应的物品已经不存在");
                }
            }

            eSell.setStatus(0);
            eSell.setRemark1(eSell.getRemark2()==null?"作废原因："+remark:eSell.getRemark2()+"；作废原因："+remark);
            eSell.setModifyTime(now);
            eSellService.update(eSell);
            resultBean.setSuccess(true);
        }else
            resultBean.setMessage("过磅记录不存在");

        return resultBean;
    }
}
